import { DomUtils } from '../utils/DomUtils';

/**
 * 掘金(https://juejin.cn)阅读优化
 */
export class JueJin {

    static hostname = 'juejin.cn';

    main(pathname) {
        // 处理首页
        if (pathname === '/') {
            this.handleHome();
            return;
        }

        // 处理文章页面
        this.handleArticlePage();
    }

    /**
     * 处理文章页面
     */
    handleArticlePage() {
        const test = document.querySelector('#article-root').previousElementSibling
        console.log("🚀 ~ JueJin ~ handleArticlePage ~ test:", test)
        
        DomUtils.hide([
            '.main-header',
            // 导航条
            '.main-header-box',
            // 右侧侧边栏
            '#sidebar-container',
            '.top-banners-container'
        ]);
        // 文章标题下方的图片广告
        DomUtils.observeHide('.article', 'img')
        // 处理顶部横条广告
        DomUtils.observeHide('.view-container', '.top-banners-container', { loop: true });
        // 右下角登录提示卡片
        DomUtils.observeHide('#juejin', '.bottom-login-guide');

        DomUtils.observe('.global-component-box', ['childList'], { childList: true }, ({ observer, target }) => {
            const btnList = target.querySelectorAll('.suspension-panel > :not(.to-top-btn)');
            if (btnList.length) {
                DomUtils.hide([...btnList], 'scale');
                observer.disconnect();
            }
        });

        this.handleArticleCatalog();
    
        DomUtils.setCss('.column-view', { padding: 0 });
        DomUtils.setCss('.author-info-block', { marginBottom: 0 });
        DomUtils.setCss(['.main-area', '.recommended-area'], {
            margin: '0 auto 20px',
            width: '960px'
        });
    
        DomUtils.observeHide('.column-view', [
            // 处理左侧竖向按钮组
            '.article-suspended-panel',
            // 处理推荐区域
            { '.recommended-area': (el) => DomUtils.setCss(el, { margin: '0 auto 20px', width: '960px' }) }
        ], { loop: true });

        // 处理评论区域
        DomUtils.observe('.main-area.article-area', ['childList'], { childList: true }, ({ observer }) => {
            const commentBox = document.querySelector('#comment-box');
            if (!commentBox) return;
            DomUtils.handleComment('#comment-box', '.title', '.comment-editor', '评论 0');
            observer.disconnect();
        });
        DomUtils.setCss('.main-container', { paddingTop: 0});
        DomUtils.setBackground();
    }

    /**
     * 处理文档目录
     */
    handleArticleCatalog() {
        // 文档目录
        const catalog = document.querySelector('.article-catalog')?.cloneNode(true);
        if (!catalog) return;

        // 删除文章目录的 "收起" 按钮
        catalog.querySelector('.catalog-title .direction')?.remove();

        // 文章目录的绑定事件
        catalog.querySelectorAll('.catalog-list a').forEach(item => {
            item.onclick = () => {
                setTimeout(() => {
                    const dataId = item.getAttribute('href').replace('#', '');
                    const target = document.querySelector(`#article-root [data-id="${dataId}"]`);
                    if (target) {
                        target.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }
                }, 100);
            };
        });

        document.body.appendChild(catalog);
        DomUtils.setCss(catalog, {
            position: 'fixed',
            top: '20px',
            left: 0,
            width: '20rem',
            bottom: 0,
            padding: '20px 0',
            margin: 0,
            zIndex: 100,
            userSelect: 'none',
            transition: '0.5s',
            transform: 'translateX(-100%)',
        });

        // 文章目录内容的列表
        const catalogBody = catalog.querySelector('.catalog-body');
        DomUtils.setCss(catalogBody, { maxHeight: 'unset' });

        // 文章目录的 展开/收起 按钮
        const btn = DomUtils.createFixedButton({
            text: '展开目录',
            parent: catalog,
            css: {
                position: 'absolute',
                right: 0,
                left: 'unset',
                writingMode: 'vertical-rl',
                transform: 'translateX(100%)',
            },
            click() {
                if (catalog.style.transform === 'translateX(-100%)') {
                    // 展开目录
                    catalog.style.transform = 'none';
                    btn.style.transform = 'none';
                    btn.textContent = '收起目录';
                } else {
                    // 收起目录
                    catalog.style.transform = 'translateX(-100%)';
                    btn.style.transform = 'translateX(100%)';
                    btn.textContent = '展开目录';
                }
            }
        });
    }

    /**
     * 处理首页
     */
    handleHome() {
        // 删除底部登录弹窗
        deleteLoginGuide();
        // 删除右侧边栏广告
        DomUtils.observe('aside.index-aside.aside', ['childList'], { childList: true }, ({ observer, target }) => {
            const banner = target.querySelectorAll('.sidebar-block.banner-block');
            if (banner && banner.length) {
                banner.forEach(item => item?.remove());
                observer.disconnect();
            }
        });
    }
}